import axios from 'axios';

const API_URL = 'http://localhost:8080/api/admin'; // 后端管理员API基础URL

// 获取存储在localStorage中的token
const getToken = () => {
    const user = JSON.parse(localStorage.getItem('user'));
    if (user && user.token) {
        return user.token;
    }
    return null;
};

// 创建带有认证头的axios实例
const axiosInstance = axios.create();

axiosInstance.interceptors.request.use(
    (config) => {
        const token = getToken();
        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

/**
 * 获取所有用户列表
 */
const getAllUsers = () => {
    return axiosInstance.get(`${API_URL}/users`);
};

/**
 * 获取特定用户的详细信息
 * @param {number} userId - 用户ID
 */
const getUserById = (userId) => {
    return axiosInstance.get(`${API_URL}/users/${userId}`);
};

/**
 * 更新用户信息
 * @param {number} userId - 用户ID
 * @param {object} userData - 要更新的用户数据
 */
const updateUser = (userId, userData) => {
    return axiosInstance.put(`${API_URL}/users/${userId}`, userData);
};

/**
 * 删除用户
 * @param {number} userId - 要删除的用户ID
 */
const deleteUser = (userId) => {
    return axiosInstance.delete(`${API_URL}/users/${userId}`);
};

/**
 * 创建新用户
 * @param {object} userData - 新用户数据
 */
const createUser = (userData) => {
    return axiosInstance.post(`${API_URL}/users`, userData);
};

const adminService = {
    getAllUsers,
    getUserById,
    updateUser,
    deleteUser,
    createUser
};

export default adminService; 